package io.github.uicdb.et;

import com.mojang.blaze3d.vertex.PoseStack;
import com.mojang.blaze3d.vertex.VertexConsumer;
import io.github.uicdb.et.register.ElementalObject;
import io.github.uicdb.et.register.RegisterHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.MultiBufferSource;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.entity.EntityRenderers;
import net.minecraft.client.renderer.entity.NoopRenderer;
import net.minecraft.client.renderer.texture.OverlayTexture;
import net.minecraft.client.resources.MobEffectTextureManager;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.entity.EntityAttachment;
import net.minecraft.world.entity.LivingEntity;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.phys.Vec3;
import net.neoforged.bus.api.IEventBus;
import net.neoforged.fml.event.lifecycle.FMLClientSetupEvent;
import net.neoforged.neoforge.client.event.RenderLivingEvent;

import java.util.ArrayList;
import java.util.List;

public class ClientEventHandle {
    public static void handle(IEventBus modBus, IEventBus gameBus) {
        gameBus.addListener(RenderLivingEvent.Post.class, ClientEventHandle::onLivingRender);
        modBus.addListener(FMLClientSetupEvent.class, fmlCommonSetupEvent -> {
            EntityRenderers.register(ModEntityType.DEFENSE_ORB.get(), NoopRenderer::new);
            EntityRenderers.register(ModEntityType.DEFENSE_ORB_SHADOW.get(), NoopRenderer::new);
        });
    }

    private static void onLivingRender(RenderLivingEvent.Post<?, ?> event) {
        if(!ETConfig.DISPLAY_ELEMENT.get())return;
        LivingEntity entity = event.getEntity();
        float partialTick = event.getPartialTick();
        PoseStack poseStack = event.getPoseStack();
        MultiBufferSource bufferSource = event.getMultiBufferSource();
        int packedLight = event.getPackedLight();
        List<ResourceLocation> shouldRenders = new ArrayList<>();
        for (ElementalObject object : RegisterHelper.getElementalObjects()) {
            if (IElementAttachment.getDataHandler(entity).has(object.getElementHolder())) {
                shouldRenders.add(object.getIcon());
            }
        }
        if (!shouldRenders.isEmpty()) {
            MobEffectTextureManager mobeffecttexturemanager = Minecraft.getInstance().getMobEffectTextures();
            float size = 0.25f;
            float width = shouldRenders.size() * size;
            float x = -width / 2f;
            Vec3 vec3 = entity.getAttachments().getNullable(EntityAttachment.NAME_TAG, 0, entity.getViewYRot(partialTick));
            if (vec3 == null) vec3 = new Vec3(0, entity.getBbHeight(), 0);
            vec3.add(0d, shouldShowName(entity) ? 0.5d : 0.35d, 0d);
            //elementalTheory$renderBg(poseStack, bufferSource, x, width, size, vec3);
            for (ResourceLocation icon : shouldRenders) {
                renderIcons(entity, icon, poseStack, bufferSource, packedLight, partialTick, x, size, vec3);
                x += size;
            }
        }
    }

    private static void renderBg(PoseStack poseStack, MultiBufferSource buffer, float x, float width, float size, Vec3 vec3) {
        RenderType RENDER_TYPE = RenderType.END_PORTAL;
        poseStack.pushPose();
        PoseStack.Pose pose = poseStack.last();
        poseStack.translate(vec3.x, vec3.y, vec3.z);
        //poseStack.mulPose(Minecraft.getInstance().getEntityRenderDispatcher().cameraOrientation());
        VertexConsumer vertexconsumer = buffer.getBuffer(RENDER_TYPE);
        vertexconsumer.addVertex(pose, x, 0f, 0.0F);
        vertexconsumer.addVertex(pose, x + width, 0f, 0.0F);
        vertexconsumer.addVertex(pose, x + width, size, 0.0F);
        vertexconsumer.addVertex(pose, x, size, 0.0F);
        poseStack.popPose();
    }

    private static void renderIcons(LivingEntity e, ResourceLocation sprite, PoseStack poseStack, MultiBufferSource buffer, int packedLight, float partialTick, float xOffset, float size, Vec3 vec3) {
        poseStack.pushPose();
        PoseStack.Pose pose = poseStack.last();
        RenderType RENDER_TYPE = RenderType.entityCutoutNoCull(sprite);
        poseStack.translate(vec3.x, vec3.y, vec3.z);
        poseStack.mulPose(Minecraft.getInstance().getEntityRenderDispatcher().cameraOrientation());
        VertexConsumer vertexconsumer = buffer.getBuffer(RENDER_TYPE);
        vertex(vertexconsumer, pose, packedLight, xOffset, 0 + 0.5f, 0, 1);
        vertex(vertexconsumer, pose, packedLight, xOffset + size, 0 + 0.5f, 1, 1);
        vertex(vertexconsumer, pose, packedLight, xOffset + size, size + 0.5f,1, 0);
        vertex(vertexconsumer, pose, packedLight, xOffset, size + 0.5f, 0, 0);

        poseStack.popPose();
    }

    private static boolean shouldShowName(LivingEntity entity) {
        if (entity instanceof Player) return false;
        return entity.shouldShowName() || entity.hasCustomName() && entity == Minecraft.getInstance().getEntityRenderDispatcher().crosshairPickEntity;
    }

    private static void vertex(VertexConsumer consumer, PoseStack.Pose pose, int packedLight, float x, float y, float u, float v) {
        consumer.addVertex(pose, x, y, 0.0F)
                .setColor(-1)
                .setUv(u, v)
                .setOverlay(OverlayTexture.NO_OVERLAY)
                .setLight(packedLight)
                .setNormal(pose, 0.0F, 1.0F, 0.0F);
    }
}
